package net.codeyouth.codegen

import net.codeyouth.codegen.bean.JavaBean
import net.codeyouth.codegen.util.DBUtil
import net.codeyouth.codegen.util.StringUtil

import java.sql.Connection
import java.sql.DatabaseMetaData
import java.sql.ResultSet
import java.sql.Statement

/**
 * Java bean provider.
 *
 * @author Frank create on 16/2/20 21:48
 */
class BeanProvider {

    // 1. 获取链接
    Connection conn

    BeanProvider() {
        this.conn = DBUtil.connection
    }

    List<JavaBean> provide() {
        def beanList = []
        def tables = getTables()
        tables.each { table ->
            beanList.add(getBean(table))
        }
        return beanList
    }


    // 2. 获取表信息 表名
    /**
     * 获取 schema 中的所有表名.
     *
     * @return List
     */
    private List<String> getTables() {
        List<String> tables = []
        Statement stmt = conn.createStatement()
        ResultSet result = stmt.executeQuery("SHOW TABLES")
        while (result.next()) {
            tables.add(result.getString(1))
        }
        result.close()
        stmt.close()
        return tables
    }

    /**
     * 根据数据库表名获取 JavaBean 类对象.
     *
     * @param tableName 表名
     * @return JavaBean类对象
     */
    private JavaBean getBean(String tableName) {
        JavaBean bean = new JavaBean()
        bean.name = StringUtil.firstUpper(StringUtil.underline2Hump(tableName))
        setFields(bean, tableName)
        return bean
    }

    // 3. 获取字段信息 字段名 类型
    /**
     * 获取指定表中的字段信息.
     *
     * @param bean Java类
     * @param tableName 表名
     */
    private void setFields(JavaBean bean, String tableName) {
        DatabaseMetaData metaData = conn.getMetaData()
        ResultSet columns = metaData.getColumns(null, null, tableName, "%")
        while (columns.next()) {
            JavaBean.Field field = new JavaBean.Field()
            // 下划线格式转为驼峰格式
            field.name = StringUtil.underline2Hump(columns.getString("COLUMN_NAME"))
            field.methodName = StringUtil.firstUpper(field.name)
            field.comment = columns.getString("REMARKS")
            field.type = DBUtil.toJavaType(columns.getString("TYPE_NAME"))
            bean.fields.add(field)
        }
        columns.close()
    }
}
